<?php

namespace app\api\logic\xiluhouse;

use app\api\logic\BaseLogic;
use app\common\model\xiluhouse\Rental;
use app\common\model\xiluhouse\RentalTag;
use app\common\model\xiluhouse\Village;
use app\common\model\xiluhouse\HouseTag;
use app\common\model\xiluhouse\HouseTagType;
use app\common\model\xiluhouse\RentalType;
use app\common\model\xiluhouse\RentalMode;
use app\common\model\xiluhouse\RentalContact;
use app\common\model\xiluhouse\HouseSearchPrice;
use app\common\model\xiluhouse\HouseSearchRoomnum;
use think\Db;
use think\Validate;
use think\exception\ValidateException;
use think\exception\PDOException;
use Exception;

class PublishRentalLogic extends BaseLogic
{
    /**
     * 发布房源
     * @param array $params
     * @return array
     */
    public function addRental($params, $user)
    {
        $validate = new Validate([
            'rental_mode_id|租赁模式' => 'require',
            'price|价格'              => 'gt:0',
            'image|封面图片'          => 'require',
            'images|房屋照片'         => 'require',
            'lease_type|租赁方式'     => 'require',
            'address|小区名称或地址'   => 'require',
            'in_time_type|入住类型'   => 'require|in:1,2,3,4', // 如 1=随时入住，2=具体日期，3=随时可搬走，4=待定
            'in_time|入住时间'        => 'require',
            // 户型 几室几厅几卫
            'room_num|几室'             => 'require',
            'ting_num|几厅'             => 'require',
            'wei_num|几卫'              => 'require',
            'space|总面积'              => 'require',
            'face|朝向'                 => 'require',
            'floor_num|楼层'            => 'require',
            'content|详情描述'          => 'require|max:800',
            // 支付方式
            'pay_type|支付方式'         => 'require',
            // 联系方式验证
            'wechat_name|微信昵称'       => 'require|max:50',
            'mobile|联系电话'           => 'require|mobile',
            'wechat_num|微信号'         => 'max:50',
            'qq_num|QQ号'              => 'max:20'
        ]);

        // 动态必填
        if ($params['rental_mode_id'] == 1) { // 直租

        } elseif ($params['rental_mode_id'] == 2) { // 合租
            $baseRules['bedroom_area|卧室面积'] = 'require';
        } elseif ($params['rental_mode_id'] == 3) { // 转租
            $baseRules['old_contract_expiration_time|旧合同到期时间'] = 'require';
        }

        if(!$validate->check($params)){
            return ['code'=>0, 'msg'=>$validate->getError()];
        }

        // 获取小区id
        $village_data = $this->getOrCreateVillageByAddress($params['address'], $params);
        if($village_data['code'] == 0){
            $this->error($village_data['msg']);
        }else{
            $params['village_id'] = $village_data['village_id'];
        }

        // 封面图片
        $params['image'] = !empty($params['image']) ? $params['image'] : '';

        // 房屋照片
        $params['images'] = !empty($params['images']) ? $params['images'] : '';

        // 入住时间
        $params['in_time'] = !empty($params['in_time']) ? strtotime($params['in_time']) : '';

        // 用户id
        $params['user_id'] = $user['id'];

        // 租房名称 小区名称
        $params['name'] = $village_data['village']['name'];

        // 处理房屋标签 house_tag_ids和rental_security_ids 合并
        if (!empty($params['rental_security_ids'])) {
            $params['house_tag_ids'] = $params['rental_security_ids'] . ',' . $params['house_tag_ids'];
        }
        $house_tag_ids = [];
        if (!empty($params['house_tag_ids'])) {
            $house_tag_ids = explode(',', $params['house_tag_ids']);
            $house_tag_ids = array_map('intval', $house_tag_ids); // 确保标签ID为整数
        }
        $params['house_tag_ids'] = implode(',', $house_tag_ids);

        // 构建标签类型映射
        $house_tag_type_ids = [];

        // 如果有标签，则获取标签类型映射
        if (!empty($house_tag_ids)) {
            // 查询这些标签所属的标签类型
            $tagInfo = HouseTag::where('id', 'in', $house_tag_ids)
                ->field('id,tag_type_id')
                ->select();
            
            foreach ($tagInfo as $tag) {
                $typeId = $tag['tag_type_id'];
                if (!isset($house_tag_type_ids[$typeId])) {
                    $house_tag_type_ids[$typeId] = $tag['id'];
                } else {
                    $house_tag_type_ids[$typeId] .= ',' . $tag['id'];
                }
            }
        }

        // 支付方式
        $params['pay_type'] = !empty($params['pay_type']) ? $params['pay_type'] : '';

        $model = new Rental();
        Db::startTrans();
        try {
            // 编辑
            if(isset($params['id']) && !empty($params['id'])){
                $row = $model->get($params['id']);
                unset($params['id']);
                $ret = $row->allowField(true)->save($params);
                // 设置房屋标签
                RentalTag::setTagIds($row,$house_tag_type_ids, 'edit');
                
                // 更新联系方式
                $contact = RentalContact::where('rental_id', $row->id)->find();
                if ($contact) {
                    // 提取并过滤联系方式数据
                    $contactData = [
                        'wechat_name' => trim($params['wechat_name']),
                        'mobile' => trim($params['mobile']),
                        'wechat_num' => isset($params['wechat_num']) ? trim($params['wechat_num']) : '',
                        'qq_num' => isset($params['qq_num']) ? trim($params['qq_num']) : '',
                    ];
                    $contact->save($contactData);
                } else {
                    // 如果不存在则创建新的联系方式
                    $this->createContact($row->id, $user['id'], $params);
                }
            }else{
                // 新增
                $ret = $model->allowField(true)->save($params);
                // 设置房屋标签
                RentalTag::setTagIds($model,$house_tag_type_ids);
                
                // 创建联系方式
                $this->createContact($model->id, $user['id'], $params);
                
                $row = $model;
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
        return ['code'=>1, 'msg'=>'success', 'data'=>$row];
    }

    /**
     * 创建联系方式
     * @param int $rental_id 房源ID
     * @param int $user_id 用户ID
     * @param array $params 参数
     * @return bool
     * @throws Exception
     */
    private function createContact($rental_id, $user_id, $params)
    {
        // 检查是否已存在联系方式
        $existingContact = Db::name('xiluhouse_rental_contact')
            ->where('rental_id', $rental_id)
            ->find();

        $now = time();
        
        if ($existingContact) {
            // 如果存在则更新
            $updateData = [
                'wechat_name' => trim($params['wechat_name']),
                'mobile' => trim($params['mobile']),
                'wechat_num' => isset($params['wechat_num']) ? trim($params['wechat_num']) : '',
                'qq_num' => isset($params['qq_num']) ? trim($params['qq_num']) : '',
                'contact_time' => isset($params['contact_time']) ? trim($params['contact_time']) : '',
                'updatetime' => $now
            ];
            
            $result = Db::name('xiluhouse_rental_contact')
                ->where('id', $existingContact['id'])
                ->update($updateData);
                
            if ($result === false) {
                throw new Exception('更新联系方式失败');
            }
            return true;
        }
        
        // 创建新联系方式
        $insertData = [
            'rental_id' => (int)$rental_id,
            'user_id' => (int)$user_id,
            'wechat_name' => trim($params['wechat_name']),
            'mobile' => trim($params['mobile']),
            'wechat_num' => isset($params['wechat_num']) ? trim($params['wechat_num']) : '',
            'qq_num' => isset($params['qq_num']) ? trim($params['qq_num']) : '',
            'contact_time' => isset($params['contact_time']) ? trim($params['contact_time']) : '',
            'is_default' => 0,
            'status' => 'normal',
            'createtime' => $now,
            'updatetime' => $now
        ];

        $result = Db::name('xiluhouse_rental_contact')->insert($insertData);
        if (!$result) {
            throw new Exception('保存联系方式失败');
        }
        
        return true;
    }

    /**
     * 通过address和详细信息查找或新增小区，返回小区id
     * @param string $address
     * @param array $extraData 可选，新增时补充字段（如name,lat,lng等）
     * @return array ['code'=>1, 'village_id'=>int, 'village'=>$village] 或 ['code'=>0, 'msg'=>'xxx']
     */
    public function getOrCreateVillageByAddress($address, $extraData = [])
    {
        // 优先用extraData中的name
        $name = !empty($extraData['name']) ? $extraData['name'] : $address;
        if (empty($name)) {
            return ['code'=>0, 'msg'=>'小区名称不能为空'];
        }

        // 检查经纬度
        if (empty($extraData['lat']) || empty($extraData['lng'])) {
            return ['code'=>0, 'msg'=>'经纬度信息不能为空'];
        }

        // 先查找是否存在同名小区
        $village = Village::where('name', $name)->find();
        if ($village) {
            return ['code'=>1, 'village_id'=>$village->id, 'village'=>$village];
        }

        // 获取省市信息
        $addrInfo = getAddr($extraData['lat'], $extraData['lng']);
        if (empty($addrInfo)) {
            return ['code'=>0, 'msg'=>'无法获取地址行政区划信息'];
        }

        // 新增小区，补全所有字段
        $data = [
            'name' => $name,
            'prov' => $addrInfo['prov'],
            'city' => $addrInfo['city'],
            'lat' => $extraData['lat'],
            'lng' => $extraData['lng'],
            'status' => 'normal',
            'check_status' => 1,
            'createtime' => time()
        ];

        // 合并其他可选字段
        $optionalFields = [
            'region', 'street', 'addr', 
            'subway_platform_id', 'subway_ids', 'subway_distance', 'subway_distance_text',
            'nearby_bus_num', 'nearby_subway_num', 'nearby_school_num', 'nearby_shop_num', 'nearby_hospital_num',
            'nearby_bus_json', 'nearby_subway_json', 'nearby_school_json', 'nearby_shop_json', 'nearby_hospital_json',
            'weigh'
        ];
        foreach ($optionalFields as $field) {
            if (isset($extraData[$field])) {
                $data[$field] = $field === 'lat' || $field === 'lng' ? floatval($extraData[$field]) : $extraData[$field];
            }
        }

        $model = new Village();
        $res = $model->allowField(true)->save($data);
        if ($res) {
            return ['code'=>1, 'village_id'=>$model->id, 'village'=>$model];
        } else {
            return ['code'=>0, 'msg'=>'新增小区失败'];
        }
    }

    /**
     * 获取参数
     * 
     */
    public function getParams()
    {
        // 房屋属性
        $where = [];
        // $where['status'] = 'normal';
        $where['type'] = 2;
        $data = HouseTagType::where($where)->field('id,name,type')->select();

        if($data){
            foreach ($data as $key => $value) {
                $where = [];
                $where['classify'] = $value['type'];
                $where['tag_type_id'] = $value['id'];
                $where['status'] = 'normal';
                $data[$key]['item'] = HouseTag::where($where)->field('id,name')->order('weigh desc')->select();
            }
        }

        // 房屋标签
        $where = [];
        $where['classify'] = 2;
        $where['tag_type_id'] = 2;
        $where['status'] = 'normal';
        $label = HouseTag::where($where)->field('id,name')->order('weigh desc')->select();

        // 支付类型
        $where = [];
        $where['status'] = 'normal';
        $pay_type = RentalType::where($where)->field('id,name')->order('weigh desc')->select();

        // 租赁类型 rental_mode
        $where = [];
        $where['status'] = 'normal';
        $rental_mode = RentalMode::where($where)->field('id,name,subtitle')->order('weigh desc')->select();

        // 租金筛选参数
        $where = [];
        $where['status'] = 'normal';
        $where['classify'] = 2;
        $rental_price = HouseSearchPrice::where($where)->field('id,name,min_price,max_price')->order('weigh desc')->select();

        // 户型筛选参数
        $where = [];
        $where['status'] = 'normal';
        $rental_roomnum = HouseSearchRoomnum::where($where)->field('id,name,min_room_num,max_room_num')->order('weigh desc')->select();

        $result = [
            'pay_type'  => $pay_type,
            'tag'       => $data,
            'label'     => $label,
            'rental_mode' => $rental_mode,
            'rental_price' => $rental_price,
            'rental_roomnum' => $rental_roomnum
        ];

        return $result;
    }

    /**
     * 上下架
     */
    public function multi_status($params, $user){
        $rental_id = array_get($params,'rental_id');
        $status = array_get($params,'status');
        if(!$rental_id || !$status || !in_array($status,['normal','hidden'])){
            return ['code'=>0, 'msg'=>'参数错误'];
        }
        $where['user_id'] = $user['id'];
        $row = Rental::where('id',$rental_id)->where($where)->find();
        if(!$row){
            return ['code'=>0, 'msg'=>'无权操作'];
        }
        if(($status == 'hidden' && in_array($row->status,['normal'])) || ($status == 'normal' && in_array($row->status,['hidden']))){
            $row->status = $status;
            $row->allowField(true)->save();
        }else{
            return ['code'=>0, 'msg'=>'状态不可操作'];
        }
        return ['code'=>1, 'msg'=>'success', 'data'=>$row];
    }
} 